package com.libraryManage.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.libraryManage.commons.config.Const;
import com.libraryManage.commons.utils.MVCUtil;
import com.libraryManage.commons.utils.PageUtil;
import com.libraryManage.commons.utils.ResponseEntity;
import com.libraryManage.commons.utils.jwt.AccountProfile;
import com.libraryManage.commons.utils.jwt.JwtUtils;
import com.libraryManage.entity.LoginLogDo;
import com.libraryManage.entity.ManagerDo;
import com.libraryManage.mapper.ManagerDoMapper;
import com.libraryManage.service.LoginService;
import com.libraryManage.vo.ManagerVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    ManagerDoMapper managerDoMapper;

    @Autowired
    JwtUtils jwtUtils;

    /**
     * 管理员登录接口
     * @param vo
     * @param response
     * @return
     */
    @Override
    public ResponseEntity<AccountProfile> managerLogin(ManagerVo vo,
                                                       HttpServletResponse response,
                                                       HttpServletRequest request) {
        //数据校验
        ManagerDo managerDo = managerDoMapper.selectByPrimaryKey(vo.getId());
        log.info(managerDo.getName());
        //isNull：如果此类不为空则new IllegalArgumentException
        //notNull反之
//        Assert.isNull(managerDo,"用户不存在");
        Assert.notNull(managerDo,"用户不存在！！");
        //SecureUtil.md5(vo.getPassword())
        if(!managerDo.getPassword().equals(vo.getPassword())){
            return MVCUtil.resFailure(Const.STAT_DATAVALIDNOPASS,"数据有效性检查不通过",null);
        }
        String token = jwtUtils.generateToken(vo.getId());
        //刷新jwt
        response.setHeader("Authorization",token);
        response.setHeader("Access-control-Expose-Headers","Authorization");
        AccountProfile res = new AccountProfile();
        BeanUtils.copyProperties(managerDo,res);
        //创建登录信息
        creatLoginLog(request,managerDo);
        return MVCUtil.response(res);
    }

    /**
     * 获取登录日志
     * @param loginLogDo
     * @return
     */
    @Override
    public ResponseEntity<List<LoginLogDo>> getLogData(LoginLogDo loginLogDo) {
        PageUtil.startPage(loginLogDo);
        List<LoginLogDo> list = managerDoMapper.getLogData(loginLogDo);
        return PageUtil.tranferPage(list);
    }

    /**
     * 创建管理员登录信息
     * @param request
     */
    private void creatLoginLog(HttpServletRequest request,
                               ManagerDo managerDo) {

        LoginLogDo loginfo = new LoginLogDo();
        //获取ip地址
        loginfo.setIpAddress(getIpAddr(request));
        //登录时间
        loginfo.setLoginTime(new Date());
        //用户名
        loginfo.setUserName(managerDo.getName());
        //用户权限
        loginfo.setRoleName(managerDo.getRoleName());
        Integer state = 0;
        state = managerDoMapper.createLoginLog(loginfo);
        if(state == 0 ){
            log.info("创建登录日志失败");
        }else {
            log.info("创建登录日志成功");
        }

    }

    /**
     * 获取ip地址
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

}
